﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperListEx.ItemLists;
using System.Windows.Forms;

namespace SuperListEx
{
    public class ColumnComparer : IComparer<object>
    {
        #region vars
        private readonly BetterItemList _list;
        private readonly Column[] _groupByColumns;
        private readonly Column[] _sortByColumns;
        #endregion

        #region Constructors
        public ColumnComparer(Column[] groupByColumns, Column[] sortByColumns, BetterItemList list)
        {
            _list = list;
            _groupByColumns = groupByColumns;
            _sortByColumns = sortByColumns;
        }
        #endregion

        #region Compare
        public int Compare(object x, object y)
        {
            foreach (Column _column in _groupByColumns)
            {
                int result = _column.GroupedComparitor(x, y);
                if (result != 0)
                {
                    return _column.GroupSortOrder == SortOrder.Descending ? -result : result;
                }
            }

            if (_sortByColumns.Length == 0)
            {
                foreach (Column column in _groupByColumns)
                {
                    int result = column.Comparitor(x, y);
                    if (result != 0)
                    {
                        return column.GroupSortOrder == SortOrder.Descending ? -result : result;
                    }
                }
            }
            else
            {
                foreach (Column column in _sortByColumns)
                {
                    int result = column.Comparitor(x, y);
                    if (result != 0)
                    {
                        return column.SortOrder == SortOrder.Descending ? -result : result;
                    }
                }
            }

            if (_list.ObjectComparer != null)
            {
                return _list.ObjectComparer.Compare(x, y);
            }
            else if (x is IComparable)
            {
                return ((IComparable)x).CompareTo(y);
            }
            else
            {
                return x.GetHashCode().CompareTo(y.GetHashCode());               
            }
        }
        #endregion
    }
}
